package com.polaris.live.dialog_fragment.room_background.fragment

import android.os.Bundle
import androidx.recyclerview.widget.GridLayoutManager
import com.lxj.xpopup.XPopup
import com.polaris.live.R
import com.polaris.live.adapter.backpack.RoomBackgroundCommodityAdapter
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.databinding.FragmentRoomBackgroundShoppingBinding
import com.polaris.live.popup.CommodityPopup
import com.polaris.live.resp.back_resp.PayerShopResp
import com.polaris.live.viewmodel.backpack.CommodityModel

/**
 * 房间背景商场
 *
 * @author Created by 半仙 on 2024/12/18/018 14:53
 */
class RoomBackgroundShoppingFragment : BaseVbFragment<CommodityModel, FragmentRoomBackgroundShoppingBinding>() {

    private val mCommodityAdapter by lazy { RoomBackgroundCommodityAdapter() }

    //展示页面回调
    private var onBuyShowCallback: (() -> Unit)? = null
    fun setOnBuyShowCallback(l: () -> Unit) {
        onBuyShowCallback = l
    }

    private var onBuySuccessCallback: (() -> Unit)? = null
    fun setOnBuySuccessCallback(l: () -> Unit) {
        onBuySuccessCallback = l
    }

    override fun initView(savedInstanceState: Bundle?) {
        mViewModel.setObjectType(CommonConst.DressUp.PARTY_BACKGROUND.toInt())
        mBinding.commodityRecycler.setEnableRefresh(false)
        mBinding.commodityRecycler.setEmptyTip(
            R.drawable.family_empty,
            getString(com.polaris.live.translation.R.string.no_hava_data)
        )
        mBinding.commodityRecycler.apply {
            recycler.apply {
                itemAnimator = null
                adapter = mCommodityAdapter
                layoutManager = GridLayoutManager(context, 2)
            }
            attachedAdapter(mCommodityAdapter, mViewModel).observe(
                this@RoomBackgroundShoppingFragment,
                mViewModel.shopListLiveData
            )
        }
        initListener()
    }

    override fun initData() {
        super.initData()
        mViewModel.onRefresh()
    }

    private fun initListener() {
        mCommodityAdapter.setOnItemClickListener { _, _, position ->
            mCommodityAdapter.setSelect(position)
            mCommodityAdapter.getItemOrNull(position)?.let {
                showCommodityPopup(it)
            }
        }
    }

    private fun showCommodityPopup(
        item: PayerShopResp,
    ) {
        XPopup.Builder(context)
            .moveUpToKeyboard(false)
            .isDestroyOnDismiss(true)
            .hasShadowBg(false)
            .enableDrag(false)
            .asCustom(CommodityPopup(requireActivity(), mViewModel, item, true, onShow = {
                onBuyShowCallback?.invoke()
            }, mBuySuccess = {
                //通知有效列表更新
                onBuySuccessCallback?.invoke()
            }) {
                //回到有效tab
                onBuyShowCallback?.invoke()
            })
            .show()
    }

}